import Api from "./lib/Api"
import setTitle from "./setTitle"
import WX from "./lib/wx-share"
import "./interface"

//if(Boolean(Number(window.GD.URLparams.useMock))){
//	import('./interface.js').then(e => {
//		console.log('mock ready')
//	})
//}

const userAgent = navigator.userAgent.toLowerCase()

const isMobile = /mobile/i.test(userAgent)

const isAndroid = /android/i.test(userAgent)

const isIOS = /iphone|ipad|ipod/i.test(userAgent)

const systemVersion =
  isMobile &&
  parseInt(
    navigator.userAgent
      .toLowerCase()
      .match(/(os|android).\d/g)[0]
      .slice(-1)
  )

const isLowAndroid = isAndroid ? systemVersion < 5 : false

const isLowIOS = isIOS ? systemVersion > 4 && systemVersion < 9 : false

const isWX = /micromessenger/i.test(userAgent)

const sleep = (time = 1000) => new Promise(resolve => setTimeout(resolve, time))

const getLocal = key => JSON.parse(localStorage.getItem(key) || "{}")
const saveLocal = (key, value) => localStorage.setItem(key, JSON.stringify(value))
const removeLocal = key => localStorage.removeItem(key)

const getSession = key => JSON.parse(sessionStorage.getItem(key) || "{}")
const saveSession = (key, value) => sessionStorage.setItem(key, JSON.stringify(value))
const removeSession = key => sessionStorage.removeItem(key)

let params = window.GD.URLparams

Api.config({
  methods: "POST", // GET POST ...
  dataType: "json", //json || jsonp
  domain: '',
  useMock: Number(params.useMock) || false,
  urlModel: 1,
  debug: Boolean(Number(params.debug)) || false
})

let fromGame = {
  from_id: params.from || "0", //来源渠道id
  pf: isAndroid ? 1 : isIOS ? 2 : 3 //1/2/3 =>安卓/ios/其他
}



const checkResCode = res => {}

const ajax = (...arg) => {
  return new Promise((resolve, reject) => {
    Api.require(...arg)
      .then(res => {
        if (res.code != 0) {
          checkResCode(res)
        }
        resolve(res)
      })
      .catch(e => {})
  })
}

const uuid = () => {
  const S4 = () => (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1)
  return S4() + S4() + "QK" + S4() + "QK" + S4() + "QK" + S4() + "QK" + S4() + S4() + S4()
}

export default {
  ajax,
  isAndroid,
  isIOS,
  isLowAndroid,
  isLowIOS,
  isWX,
  sleep,
  getLocal,
  saveLocal,
  removeLocal,
  getSession,
  saveSession,
  removeSession,
  fromGame,
  WX,
  setTitle,
  uuid
}
